package cc.rengu.igas.bomp.core.realize.impl;

import cc.rengu.igas.bomp.common.dao.BompDevBindInfoMapper;
import cc.rengu.igas.bomp.common.dao.BompMchntBindInfoMapper;
import cc.rengu.igas.bomp.common.dao.BompUserInfoMapper;
import cc.rengu.igas.bomp.common.dao.ManagerInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.BompDevBindInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.BompMchntBindInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.BompUserInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.ManagerInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.BspsDevBindInfo;
import cc.rengu.igas.bomp.common.entity.BspsMchntBindInfo;
import cc.rengu.igas.bomp.common.entity.BspsUserInfo;
import cc.rengu.igas.bomp.common.entity.ManagerInfo;
import cc.rengu.igas.bomp.common.enums.MchntTypeEnum;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.realize.BspsPublicService;
import cc.rengu.igas.share.common.enums.BindStatusEnum;
import cc.rengu.igas.share.core.model.DevBindInfo;
import cc.rengu.igas.share.core.model.MchntBindInfo;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by wangcheng on 2021/10/14 17:10
 */
public class BspsPublicServiceImpl implements BspsPublicService {
    private final RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    @Override
    public List<MchntBindInfo> getMchntBindInfo(String instId, String userId, String mchntNo) throws Exception {
        /* 参数合法性检查 */
        if (StringUtil.isEmptyOrNull(instId) || (StringUtil.isEmptyOrNull(userId) && StringUtil.isEmptyOrNull(mchntNo))) {
            rglog.error("参数必填性校验失败！instId:<{}>,userId:<{}>,mchntNo:<{}>", instId, userId, mchntNo);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /* 获取用户绑定信息及对应角色权限 */
        BompMchntBindInfoMapper bompMchntBindInfoMapper = new BompMchntBindInfoMapperImpl();
        List<BspsMchntBindInfo> bspsMchntBindInfoList;
        if (!StringUtil.isEmptyOrNull(mchntNo)) {
            bspsMchntBindInfoList = bompMchntBindInfoMapper.selectBompMchntBindInfoByMchntNo(instId, mchntNo);
            if (CollectionUtils.isEmpty(bspsMchntBindInfoList)) {
                /* 用户为连锁商户法人(新增门店) */
                bspsMchntBindInfoList = bompMchntBindInfoMapper.selectBompMchntBindInfoListByUserId(instId, userId);
                if (!CollectionUtils.isEmpty(bspsMchntBindInfoList)) {
                    bspsMchntBindInfoList = bspsMchntBindInfoList.stream().filter(item -> MchntTypeEnum.CHAIN_MCHNT.getMchntType().equals(item.getBindMchntType())).collect(Collectors.toList());
                }
            } else if (!StringUtil.isEmptyOrNull(userId)) {
                bspsMchntBindInfoList = bspsMchntBindInfoList.stream().filter(item -> userId.equals(item.getBindUserId())).collect(Collectors.toList());
            }
        } else {
            bspsMchntBindInfoList = bompMchntBindInfoMapper.selectBompMchntBindInfoListByUserId(instId, userId);
        }

        List<MchntBindInfo> mchntBindInfoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bspsMchntBindInfoList)) {
            rglog.info("商户绑定关系赋值开始");
            for (BspsMchntBindInfo bspsMchntBindInfo : bspsMchntBindInfoList) {
                MchntBindInfo mchntBindInfo = new MchntBindInfo();
                BeanUtil.beanCopy(bspsMchntBindInfo, mchntBindInfo);
                mchntBindInfo.setMchntType(bspsMchntBindInfo.getBindMchntType());
                mchntBindInfoList.add(mchntBindInfo);
            }
        }
        return mchntBindInfoList;
    }

    @Override
    public boolean mchntUnBind(String instId, String userId, String mchntNo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId)) {
            rglog.error("必填性校验失败！");
            return false;
        }
        /*根据用户标识查询拓展经理用户信息*/
        BompUserInfoMapper bompUserInfoMapper = new BompUserInfoMapperImpl();
        BspsUserInfo bspsUserInfo = bompUserInfoMapper.selectBompBspsUserInfoByUserId(instId, userId);
        if (null == bspsUserInfo || StringUtil.isEmptyOrNull(bspsUserInfo.getOpenId())) {
            rglog.error("用户信息查询失败！");
            return false;
        }
        /*根据用户openId查询拓展经理信息*/
        String channelId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.CHANNEL_ID);
        ManagerInfo managerInfo = null;
        ManagerInfoMapper managerInfoMapper = new ManagerInfoMapperImpl();
        if ("APP".equals(channelId)){
            managerInfo = managerInfoMapper.selectManagerInfoById(instId,userId);
        }else {
            managerInfo = managerInfoMapper.selectManagerInfoByOpenId(instId, bspsUserInfo.getOpenId());
        }
        if (null == managerInfo) {
            rglog.error("拓展经理信息查询失败！");
            return false;
        }
        int iRturnCode;
        /*更新拓展经理信息*/
        managerInfo.setOpenId("OPENID");
        managerInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        managerInfo.setLastOprId(userId);
        iRturnCode = managerInfoMapper.updateManagerInfoById(managerInfo);
        if (0 != iRturnCode) {
            rglog.error("拓展经理信息更新失败！");
            return false;
        }
        /*更新用户表*/
        bspsUserInfo.setUserStatus("01");
        bspsUserInfo.setLastOprId(userId);
        bspsUserInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        iRturnCode = bompUserInfoMapper.updateBompBspsUserInfoByPrimaryKey(bspsUserInfo);
        if (0 != iRturnCode) {
            rglog.error("用户信息信息更新失败！");
            return false;
        }
        return true;
    }

    @Override
    public List<DevBindInfo> getDevBindInfo(String instId, String userId, String mchntNo) throws Exception {
        /*必填校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(mchntNo)) {
            rglog.error("必填性校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*查询收银员信息*/
        List<MchntBindInfo> mchntBindInfoList = getMchntBindInfo(instId, mchntNo, userId);
        List<DevBindInfo> bindDevInfoList = new ArrayList<>();
        /*根据收银员信息及绑定设备类型查询收银员绑定设备信息*/
        if (!CollectionUtils.isEmpty(mchntBindInfoList)) {
            BompDevBindInfoMapper bompDevBindInfoMapper = new BompDevBindInfoMapperImpl();
            for (MchntBindInfo mchntBindInfo : mchntBindInfoList) {
                List<BspsDevBindInfo> bspsDevBindInfoList = bompDevBindInfoMapper.selectBompDevBindInfoListByMchntNo(mchntBindInfo.getInstId(), mchntBindInfo.getMchntNo());
                if (!CollectionUtils.isEmpty(bspsDevBindInfoList)) {
                    for (BspsDevBindInfo bspsDevBindInfo : bspsDevBindInfoList) {
                        DevBindInfo devBindInfo = new DevBindInfo();
                        /*收银员绑定设备信息拼装*/
                        devBindInfo.setBindUserId(bspsDevBindInfo.getBindUserId());
                        devBindInfo.setBindDevId(bspsDevBindInfo.getBindDevId());
                        devBindInfo.setBindDevModel(bspsDevBindInfo.getBindDevModel());
                        devBindInfo.setBindStatus(bspsDevBindInfo.getBindStatus());
                        devBindInfo.setMsgPushFlag(bspsDevBindInfo.getMsgPushFlag());
                        bindDevInfoList.add(devBindInfo);
                    }
                }
            }
            return bindDevInfoList;
        }
        return null;
    }

    @Override
    public boolean devUnBind(String instId, String userId, String mchntNo) throws Exception {
        if (StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo)) {
            rglog.error("请求参数校验必填字段失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*解绑操作：1-判断用户是否拥有解绑设备的权限 2-进行解绑操作*/
        /*1-查询设备绑定信息:现有逻辑基于现有业务一个设备只能绑定一个用户，如改成一个设备可以绑定多个收银员时解绑需上送被解绑人ID*/
        /*根据法人行、设备唯一标识和设备类型查询设备绑定收银员ID*/
        BompDevBindInfoMapper bompDevBindInfoMapper = new BompDevBindInfoMapperImpl();
        List<BspsDevBindInfo> bspsDevBindInfoList = bompDevBindInfoMapper.selectBompDevBindInfoListByMchntNo(instId, mchntNo);
        if (CollectionUtils.isEmpty(bspsDevBindInfoList)) {
            rglog.error("语音设备信息查询失败！userId:<{}>,mchntNo:<{}>", userId, mchntNo);
            return false;
        }
        bspsDevBindInfoList = bspsDevBindInfoList.stream().filter(item -> item.getBindStatus().equals("00") && item.getBindUserId().equals(userId)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(bspsDevBindInfoList)) {
            rglog.error("用户没有绑定的设备！userId:<{}>,mchntNo:<{}>", userId, mchntNo);
            return false;
        }
        BspsDevBindInfo bspsDevBindInfo = bspsDevBindInfoList.get(0);
        /*2-进行设备解绑操作*/
        bspsDevBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
        /*最后操作人信息*/
        bspsDevBindInfo.setLastOprId(userId);
        bspsDevBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        int iReturnCode = bompDevBindInfoMapper.updateBompDevBindInfoByMchntStopOrCancel(bspsDevBindInfo);
        if (0 != iReturnCode) {
            rglog.error("解绑语音设备失败,iReturnCode:<{}>", iReturnCode);
            return false;
        }
        return true;
    }
}
